package com.atguigui.leetcode;

/**
 * 31.下一个排列
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by  wangjiaxin  on 2022/7/3 17:48
 */
public class P31NextPermutation {
    public static void main(String[] args) {
        Solution solution = new P31NextPermutation().new Solution();
        // TO TEST
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public void nextPermutation(int[] nums) {


            // 右边开始第一个较小的数
            int i = nums.length - 2;
            while (i >= 0 && nums[i] >= nums[i + 1]) {
                i--;
            }
            if (i >= 0) {
                // 右边开始第一个比 i 较大的数
                int j = nums.length - 1;
                while (j >= 0 && nums[i] >= nums[j]) {
                    j--;
                }
                //互换这两个数
                swap(nums, i, j);
            }

            // i 以后的数肯定是降序排列
            // 使互换后 i 以后的数从小到大排序
            reverse(nums, i + 1);

        }

        private void reverse(int[] nums, int start) {
            int left = start, right = nums.length - 1;
            while (left < right) {
                swap(nums, left, right);
                left++;
                right--;
            }
        }

        private void swap(int[] nums, int i, int j) {
            int num = nums[i];
            nums[i] = nums[j];
            nums[j] = num;
        }
    }
}
